package grpcserver

import (
	"context"
	"time"

	alertv1 "github.com/devops-smartbot/devops-smartbot/proto/gen/go/alert/v1"
	"github.com/devops-smartbot/devops-smartbot/services/alert-service/internal/service"
)

// Server implements the AlertServiceServer API.
type Server struct {
	alertv1.UnimplementedAlertServiceServer
	service service.Service
}

// New constructs a new gRPC server.
func New(service service.Service) *Server {
	return &Server{service: service}
}

// ListAlerts delegates to service layer and maps response types.
func (s *Server) ListAlerts(ctx context.Context, req *alertv1.ListAlertsRequest) (*alertv1.ListAlertsResponse, error) {
	alerts, total, err := s.service.ListAlerts(ctx, req)
	if err != nil {
		return nil, err
	}

	resp := &alertv1.ListAlertsResponse{Total: int32(total)}
	for _, a := range alerts {
		resp.Alerts = append(resp.Alerts, &alertv1.Alert{
			Id:           a.ID,
			Fingerprint:  a.Fingerprint,
			Name:         a.Alertname,
			Severity:     a.Severity,
			Status:       a.Status,
			Instance:     a.Instance,
			Description:  a.Description,
			StartsAtUnix: a.StartsAt.Unix(),
			EndsAtUnix:   a.EndsAt.Unix(),
			Labels:       a.Labels,
			Annotations:  a.Annotations,
		})
	}

	return resp, nil
}

// GetAlert returns a single alert.
func (s *Server) GetAlert(ctx context.Context, req *alertv1.GetAlertRequest) (*alertv1.Alert, error) {
	alert, err := s.service.GetAlert(ctx, req.GetId())
	if err != nil {
		return nil, err
	}
	if alert == nil {
		return nil, nil
	}

	res := &alertv1.Alert{
		Id:           alert.ID,
		Fingerprint:  alert.Fingerprint,
		Name:         alert.Alertname,
		Severity:     alert.Severity,
		Status:       alert.Status,
		Instance:     alert.Instance,
		Description:  alert.Description,
		StartsAtUnix: alert.StartsAt.Unix(),
		EndsAtUnix:   alert.EndsAt.Unix(),
		Labels:       alert.Labels,
		Annotations:  alert.Annotations,
	}

	return res, nil
}

func unixPtr(t *time.Time) int64 {
	if t == nil {
		return 0
	}
	return t.Unix()
}
